package com.imooc.ecommerce.util;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.imooc.ecommerce.constant.CommonConstant;
import com.imooc.ecommerce.vo.LoginUserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Calendar;
import java.util.Objects;

/**
 * <p>JWT Token 解析工具类
 *
 * @author Yaxi.Zhang
 * @since 2022/11/2 01:18
 */
public class TokenParseUtil {
    /**
     * <p>从 JWT Token 中解析 LoginUserInfo 对象
     */
    public static LoginUserInfo parseUserInfoFromToken(String token) throws Exception {
        if (null == token) {
            return null;
        }
        // 通过公钥去解析 JWT Token
        Claims body = Jwts.parser().setSigningKey(getPublicKey()).parseClaimsJws(token).getBody();

        // 如果 Token 已经过期了, 返回 null
        if (Objects.nonNull(body.getExpiration()) && body.getExpiration().before(Calendar.getInstance().getTime())) {
            return null;
        }
        // 返回 Token 中保存的用户信息
        return JSON.parseObject(body.get(CommonConstant.JWT_USER_INFO_KEY).toString(), LoginUserInfo.class);
    }

    /**
     * <p>根据本地存储的公钥获取到 PublicKey 对象
     */
    private static PublicKey getPublicKey() throws Exception {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decode(CommonConstant.PUBLIC_KEY));
        return KeyFactory.getInstance("RSA").generatePublic(keySpec);
    }
}
